package org.example.test2;

import org.apache.zookeeper.KeeperException;

import java.io.IOException;

public class DistributedLockTest {
    public static void main(String[] args) {
        // 记得在 zookeeper 上创建对应节点
        String path = "/lock";
        final DistributedLock lock1 = new DistributedLock(path);
        final DistributedLock lock2 = new DistributedLock(path);
        new Thread(() -> {
            try {
                lock1.connect();
                lock1.zkLock();
                System.out.println("线程" + Thread.currentThread().getName() + " 加锁...");
                Thread.sleep(5 * 1000);
                System.out.println("线程" + Thread.currentThread().getName() + " 释放锁...");
                lock1.zkUnlock();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            }
        }).start();
        new Thread(() -> {
            try {
                lock2.connect();
                lock2.zkLock();
                System.out.println("线程" + Thread.currentThread().getName() + " 加锁...");
                Thread.sleep(5 * 1000);
                System.out.println("线程" + Thread.currentThread().getName() + " 释放锁...");
                lock2.zkUnlock();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
}
